/**
 * @Project: Runer
 * @Title: ActivityChat.java
 * @Package com.runlooker.runer.activity.chat
 * @author town
 * @date 2014-6-15 上午11:06:37
 * @Copyright: 2014 www.yineng.com.cn Inc. All rights reserved.
 * @version V1.0
 */
package com.runlooker.runer.ui.chat;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smackx.filetransfer.FileTransfer.Status;

import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.support.v4.util.LruCache;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.runlooker.runer.R;
import com.runlooker.runer.application.MyApplication;
import com.runlooker.runer.dao.ChatMsgDao;
import com.runlooker.runer.entity.ChatMsgEntity;
import com.runlooker.runer.imageloader.ImageChooseActivity;
import com.runlooker.runer.interfaces.FileReciveStatusListener;
import com.runlooker.runer.interfaces.FileSendStantusListener;
import com.runlooker.runer.interfaces.MessageListener;
import com.runlooker.runer.service.XmppService;
import com.runlooker.runer.util.L;
import com.runlooker.runer.util.RecordUtil;
import com.runlooker.runer.util.T;
import com.runlooker.runer.util.TimeUtil;

/**
 * @ClassName ActivityChat
 * @Description 模块描述
 * @author town
 * @Date 2014-6-15
 */
@SuppressLint("CutPasteId")
public class ChatActivity extends FragmentActivity implements OnClickListener,
		MessageListener, FileSendStantusListener, FileReciveStatusListener {
	public static final String CHOOSE_IMAGE_PATHS = "choose_image_paths";// 选择图片的路径列表
	public static final String TEMP_DIR = "ChatActivity_temp_dir"
			+ File.separator;// 临时文件夹名称
	private static final int MAX_TIME = 60;// 最长录音时间
	private static final int MIN_TIME = 1;// 最短录音时间

	// handle处理的状态
	private static final int RECORD_UPDATE_ANIMATION = 0;// 录音时，音量大小的动画显示效果
	public static final int GET_MESSAGE = 1;// 获得消息(包含普通消息、图片、录音文件)
	private static final int RECORD_OVER = 2; // 录音结束
	private static final int SEND_RECORD_FILE_SUCCESS = 3;// 成功发送录音文件
	private static final int SEND_RECORD_FILE_ING = 4;// 正在发送录音文件.
	private static final int SEND_RECORD_FILE_FAILED = 5;// 发送录音文件失败.
	public static final int SEND_COMMON_MESSAGE_EXCEPTION = 6;// 发送普通消息异常
	public static final int SEND_COMMON_MESSAGE_SUCCESS = 7;// 成功发送普通消息
	public static final int SEND_COMMON_MESSAGE_ING = 8;// 正在发送普通消息
	public static final int SEND_IMAGE_FILE_SUCCESS = 9;// 成功发送图片
	private static final int SEND_IMAGE_FILE_ING = 10;// 正在发送图片文件.
	private static final int SEND_IMAGE_FILE_FAILED = 11;// 发送图片失败.
	private static final int PULL_OVER = 12;// 下拉刷新UI
	private static final int PLAY_VOICE_OVER = 13;// 播放音乐结束

	// 录音时的状态
	private static final int RECORD_NO = 0; // 不在录音
	private static final int RECORD_ING = 1; // 正在录音
	private static final int RECORD_ED = 2; // 完成录音

	// 打开图片选择器的请求码和返回结果码
	public static final int CONFIRM_RESULT_OK = 1;// 选择了图片
	public static final int CONCEL_RESULT_CODE = 2;// 取消选择图片
	private static final int REQUESTCODE = 0;// 打开图片选择界面的请求码

	private static final String tag = ChatActivity.class.getSimpleName();
	// 启动该页面所需要的参数
	public static final String INTENT_ACCOUNT = "account";// 用户帐号

	private static final int PAGE_SIZE = 5;// 每次刷新的数据

	private ArrayList<String> mImagePathList = new ArrayList<String>();
	private LinkedList<ChatMsgEntity> msgList = new LinkedList<ChatMsgEntity>();
	public SendMessageQueue mSendMessageQueue = new SendMessageQueue();
	private SendMsgThread mSendMsgThread = new SendMsgThread();

	private RecordUtil mRecordUtil;

	private View view;
	private ImageView mOpenRecordIV;
	private ImageView mRecordVolume;
	private ImageView mSelectBtn;
	private TextView mSendTV;
	private TextView mRecordTV;
	private TextView mRecordTime;
	private EditText mInputContentET;
	private ListView mList;
	private PullToRefreshListView mPulltorefreshlistview;
	private ProgressBar mRecordProgressBar;
	private RelativeLayout mRecordLayout;
	private RelativeLayout mTextSendLayout;
	private RelativeLayout mUtilLayout;
	private GridView mUtilGridLayout;
	private ChatMsgEntity mEntity;

	private String mRecordPath;// 录音的存储名称
	private String mChatAccount; // 聊天：对方的帐号

	private XmppService mXmppService;
	private ChatMsgDao mChatMsgDao;
	private ChatAdapter mMyAdapter;
	// private MediaPlayer mMediaPlayer;
	private boolean btn_vocie = false;
	private boolean interupt = false;// 关闭该界面线程的标识
	private boolean isBottom = true;// 标识是否是滑动到底部
	private int mImagesArray[] = null;// 下拉布局中图片选择按钮、其他按钮的图标数组
	private String texts[] = null;
	// private int mPlayCurrentPosition;// 当前播放的时间
	private int mMAXVolume;// 最大音量高度
	private int mMINVolume;// 最小音量高度
	private int mPage = 0;
	private int mRecord_State = RECORD_NO; // 录音的状态
	private float mRecord_Time;// 录音的时间
	private double mRecord_Volume;// 麦克风获取的音量值
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			ChatMsgEntity entity;
			switch (msg.what) {
			case RECORD_OVER:// 录音结束
				if (mRecord_State == RECORD_ING) {
					// 修改录音状态
					mRecord_State = RECORD_ED;
					try {
						// 停止录音
						mRecordUtil.stop();
						// 初始化录音音量
						mRecord_Volume = 0;
					} catch (IOException e) {
						e.printStackTrace();
					}
					// 根据录音修改界面显示内容
					mRecordLayout.setVisibility(View.GONE);
					mRecordTV.setVisibility(View.GONE);
				}
				break;

			case RECORD_UPDATE_ANIMATION:
				// 根据录音时间显示进度条
				mRecordProgressBar.setProgress((int) mRecord_Time);
				// 显示录音时间
				mRecordTime.setText((int) mRecord_Time + "″");
				// 根据录音声音大小显示效果
				ViewGroup.LayoutParams params = mRecordVolume.getLayoutParams();
				if (mRecord_Volume < 200.0) {
					params.height = mMINVolume;
				} else if (mRecord_Volume > 200.0 && mRecord_Volume < 400) {
					params.height = mMINVolume * 2;
				} else if (mRecord_Volume > 400.0 && mRecord_Volume < 800) {
					params.height = mMINVolume * 3;
				} else if (mRecord_Volume > 800.0 && mRecord_Volume < 1600) {
					params.height = mMINVolume * 4;
				} else if (mRecord_Volume > 1600.0 && mRecord_Volume < 3200) {
					params.height = mMINVolume * 5;
				} else if (mRecord_Volume > 3200.0 && mRecord_Volume < 5000) {
					params.height = mMINVolume * 6;
				} else if (mRecord_Volume > 5000.0 && mRecord_Volume < 7000) {
					params.height = mMINVolume * 7;
				} else if (mRecord_Volume > 7000.0 && mRecord_Volume < 10000.0) {
					params.height = mMINVolume * 8;
				} else if (mRecord_Volume > 10000.0 && mRecord_Volume < 14000.0) {
					params.height = mMINVolume * 9;
				} else if (mRecord_Volume > 14000.0 && mRecord_Volume < 17000.0) {
					params.height = mMINVolume * 10;
				} else if (mRecord_Volume > 17000.0 && mRecord_Volume < 20000.0) {
					params.height = mMINVolume * 11;
				} else if (mRecord_Volume > 20000.0 && mRecord_Volume < 24000.0) {
					params.height = mMINVolume * 12;
				} else if (mRecord_Volume > 24000.0 && mRecord_Volume < 28000.0) {
					params.height = mMINVolume * 13;
				} else if (mRecord_Volume > 28000.0) {
					params.height = mMAXVolume;
				}
				mRecordVolume.setLayoutParams(params);
				break;
			case SEND_COMMON_MESSAGE_SUCCESS:
				entity = (ChatMsgEntity) msg.obj;
				updateOrAddAdapterData(msgList, entity);
				mMyAdapter.notifyDataSetChanged();
				isBottom = true;
				mList.setSelection(mMyAdapter.getCount());
				break;
			case SEND_COMMON_MESSAGE_EXCEPTION:
				entity = (ChatMsgEntity) msg.obj;
				updateOrAddAdapterData(msgList, entity);
				mMyAdapter.notifyDataSetChanged();
				isBottom = true;
				mList.setSelection(mMyAdapter.getCount());
				break;
			case SEND_COMMON_MESSAGE_ING:
				break;
			case SEND_RECORD_FILE_SUCCESS:
				entity = (ChatMsgEntity) msg.obj;
				updateOrAddAdapterData(msgList, entity);
				mMyAdapter.notifyDataSetChanged();
				isBottom = true;
				mList.setSelection(mMyAdapter.getCount());
				break;
			case SEND_RECORD_FILE_ING:
				break;
			case SEND_RECORD_FILE_FAILED:
				entity = (ChatMsgEntity) msg.obj;
				updateOrAddAdapterData(msgList, entity);
				mMyAdapter.notifyDataSetChanged();
				isBottom = true;
				mList.setSelection(mMyAdapter.getCount());
				break;
			case SEND_IMAGE_FILE_SUCCESS:
				entity = (ChatMsgEntity) msg.obj;
				updateOrAddAdapterData(msgList, entity);
				mMyAdapter.notifyDataSetChanged();
				isBottom = true;
				mList.setSelection(mMyAdapter.getCount());
				break;
			case SEND_IMAGE_FILE_ING:
				break;
			case SEND_IMAGE_FILE_FAILED:
				entity = (ChatMsgEntity) msg.obj;
				updateOrAddAdapterData(msgList, entity);
				mMyAdapter.notifyDataSetChanged();
				isBottom = true;
				mList.setSelection(mMyAdapter.getCount());
				break;
			case PULL_OVER:
				mPulltorefreshlistview.onRefreshComplete();
				break;
			case GET_MESSAGE:// 获得别人发送的数据，更新ui
				entity = (ChatMsgEntity) msg.obj;
				updateOrAddAdapterData(msgList, entity);
				mMyAdapter.notifyDataSetChanged();
				if (isBottom) {
					mList.setSelection(mMyAdapter.getCount());
				}
				break;
			case PLAY_VOICE_OVER:// 播放音乐结束
				entity = (ChatMsgEntity) msg.obj;
				entity.setVoicePlayStatus(ChatMsgEntity.PLAY_END);
				entity.setIsReaded(ChatMsgEntity.IS_READ);
				mChatMsgDao.saveOrUpdate(entity);
				updateOrAddAdapterData(msgList, entity);
				mMyAdapter.notifyDataSetChanged();
				getFragmentManager();
				break;
			}
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == CONFIRM_RESULT_OK) {
			mImagePathList = data.getStringArrayListExtra(CHOOSE_IMAGE_PATHS);
			for (String path : mImagePathList) {
				Message msg = new Message();
				ChatMsgEntity entity = new ChatMsgEntity();
				entity.setChatAccount(mChatAccount);
				entity.setChatType(ChatMsgEntity.PERSON_CHAT);
				entity.setIsReaded(ChatMsgEntity.IS_READ);
				entity.setIsSended(ChatMsgEntity.SENDED_ING);
				entity.setPath(path);
				entity.setMsgSourse(ChatMsgEntity.IS_SEND_MSG);
				entity.setMsgType(ChatMsgEntity.IAMGE_FILE);
				File tempFile = new File(path.trim());
				entity.setFileName(tempFile.getName());
				entity.setPacketId(msg.getPacketID());
				entity.setTime(TimeUtil.getCurrentMillisecond());
				mSendMessageQueue.putEntity(entity);
			}
		}
	}

	ServiceConnection mConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mXmppService = ((XmppService.XMPPBinder) service).getService();
			XmppService.addMessageListener(ChatActivity.this);
			XmppService.addFileSendStatusListener(ChatActivity.this);
			XmppService.addFileReciveStatusListener(ChatActivity.this);
		}

		@Override
		public void onServiceDisconnected(ComponentName arg0) {
			mXmppService = null;
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		XmppService.removeMessagelistener(this);
		XmppService.removeFileReciveStatusListener(this);
		XmppService.removeFileSendStatusListener(this);
		unbindService(mConnection);
		mHandler.removeCallbacksAndMessages(null);

		// 销毁发送线程（根据interupt ==false 和entity.packetId==null退出线程）
		interupt = true;
		ChatMsgEntity entity = new ChatMsgEntity();
		mSendMessageQueue.putEntity(entity);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);
		initialize();
	}

	private void initialize() {

		// 发送消息的线程
		mSendMsgThread.start();
		Intent intent = new Intent(this, XmppService.class);
		bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
		// 避免进入该界面就弹出键盘
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

		mMyAdapter = new ChatAdapter(this, mXmppService, msgList);
		mChatMsgDao = new ChatMsgDao(this);

		view = findViewById(R.id.ll_facechoose);
		mUtilLayout = (RelativeLayout) findViewById(R.id.ll_utilchoose);
		mUtilGridLayout = (GridView) findViewById(R.id.gv_choose_grid_layout);
		mSelectBtn = (ImageView) findViewById(R.id.btn_select);
		mRecordProgressBar = (ProgressBar) findViewById(R.id.voice_record_progressbar);
		mRecordVolume = (ImageView) findViewById(R.id.voice_recording_volume);
		mRecordTime = (TextView) findViewById(R.id.voice_record_time);
		mRecordLayout = (RelativeLayout) findViewById(R.id.voice_record_layout);
		mOpenRecordIV = (ImageView) findViewById(R.id.ivPopUp);
		mTextSendLayout = (RelativeLayout) findViewById(R.id.btn_bottom);
		mPulltorefreshlistview = (PullToRefreshListView) findViewById(R.id.lv_chat_listview);
		mList = mPulltorefreshlistview.getRefreshableView();
		mSendTV = (TextView) findViewById(R.id.btn_send);
		mInputContentET = (EditText) findViewById(R.id.et_sendmessage);
		mRecordTV = (TextView) findViewById(R.id.btn_rcd);

		// 获得上一个界面传入的对方聊天帐号（非JID格式）
		mChatAccount = getIntent().getCharSequenceExtra(INTENT_ACCOUNT)
				.toString().trim();

		mSendTV.setOnClickListener(this);
		mOpenRecordIV.setOnClickListener(this);
		mRecordTV.setOnClickListener(this);
		mList.setAdapter(mMyAdapter);

		// 设置当前的最小声音和最大声音值
		mMINVolume = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 4.5f, getResources()
						.getDisplayMetrics());
		mMAXVolume = (int) TypedValue.applyDimension(
				TypedValue.COMPLEX_UNIT_DIP, 65f, getResources()
						.getDisplayMetrics());

		// 下拉布局（进入图片选择器按钮、其他按钮）
		mImagesArray = new int[] { R.drawable.tab_address_normal };
		texts = new String[] { "发送图片" };
		ArrayList<HashMap<String, Object>> lstImageItem = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < texts.length; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("itemImage", mImagesArray[i]);
			map.put("itemText", texts[i]);
			lstImageItem.add(map);
		}
		SimpleAdapter saImageItems = new SimpleAdapter(this, lstImageItem,// 数据源
				R.layout.chat_bottom_grid_item,// 显示布局
				new String[] { "itemImage", "itemText" }, new int[] {
						R.id.itemImage, R.id.itemText });
		mUtilGridLayout.setAdapter(saImageItems);
		refreshUIByLoacalData();// 通过本地数据刷新UI
		setListener();
	}

	/**
	 * 
	 * 更新adapter里面的数据（包含同一ID的则更新，不包含，则添加到链表的尾部）
	 * 
	 * @param list
	 * @param entity
	 */
	public static void updateOrAddAdapterData(LinkedList<ChatMsgEntity> list,
			ChatMsgEntity entity) {
		for (int i = (list.size() - 1); i >= 0; i--) {
			if (entity.getPacketId().trim()
					.equals(list.get(i).getPacketId().trim())) {
				list.set(i, entity);
				return;
			}
		}
		list.addLast(entity);
	}

	/**
	 * 根据本地数据刷新UI，每次刷新PAGE_SIZE条，每次调用该方法会叠加
	 */
	private void refreshUIByLoacalData() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				List<ChatMsgEntity> list = mChatMsgDao.getEntitiesByLimit(
						mChatAccount, mPage, PAGE_SIZE);
				if (list != null && !list.isEmpty()) {
					msgList.addAll(0, list);
					mPage++;
				}
				mMyAdapter.notifyDataSetChanged();
			}
		});
	}

	private void setListener() {
		mUtilGridLayout.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				switch (arg2) {
				case 0:
					// 点击跳转图片选择器
					Intent intent = new Intent(ChatActivity.this,
							ImageChooseActivity.class);
					startActivityForResult(intent, REQUESTCODE);
					break;

				default:
					break;
				}
			}
		});
		mSelectBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (mUtilLayout.isShown()) {
					mUtilLayout.setVisibility(View.GONE);
				} else {
					mUtilLayout.setVisibility(View.VISIBLE);
				}
			}
		});
		mInputContentET.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				if (mInputContentET.getText().toString().trim().length() > 0) {
					// 输入框有输入，显示发送按钮
					mSelectBtn.setVisibility(View.GONE);
					mSendTV.setVisibility(View.VISIBLE);
				} else {
					// 输入框没有输入，显示下拉按钮
					mSelectBtn.setVisibility(View.VISIBLE);
					mSendTV.setVisibility(View.GONE);
				}
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {

			}

			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		mList.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE: //
					// 停止...
					if (view.getLastVisiblePosition() == (view.getCount() - 1)) {
						isBottom = true;
					} else {
						isBottom = false;
					}
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					// 正在滑动...
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					// 开始滚动...
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {

			}
		});
		mPulltorefreshlistview
				.setOnRefreshListener(new OnRefreshListener<ListView>() {
					@Override
					public void onRefresh(
							PullToRefreshBase<ListView> refreshView) {
						mHandler.post(new Runnable() {
							@Override
							public void run() {
								refreshUIByLoacalData();
								mHandler.sendEmptyMessage(PULL_OVER);
							}
						});
					}
				});
		mRecordTV.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch (event.getAction()) {
				// 开始录音
				case MotionEvent.ACTION_DOWN:
					mEntity = new ChatMsgEntity();
					if (mRecord_State != RECORD_ING) {
						mRecordLayout.setVisibility(View.VISIBLE);
						// 修改录音状态
						mRecord_State = RECORD_ING;

						// 设置录音保存路径
						mEntity.setFileName(UUID.randomUUID() + ".amr");

						mRecordPath = MyApplication.getVoiceSavePath()
								+ mEntity.getFileName();

						// 实例化录音工具类
						mRecordUtil = new RecordUtil(mRecordPath);
						// 开始录音
						try {
							mRecordUtil.start();
						} catch (IOException e) {
							e.printStackTrace();
						}
						new Thread(new Runnable() {
							public void run() {
								// 初始化录音时间
								mRecord_Time = 0;
								while (mRecord_State == RECORD_ING) {
									// 大于最大录音时间则停止录音
									if (mRecord_Time >= MAX_TIME) {
										mHandler.sendEmptyMessage(RECORD_OVER);
									} else {
										try {
											// 每隔200毫秒就获取声音音量并更新界面显示
											Thread.sleep(200);
											mRecord_Time += 0.2;
											if (mRecord_State == RECORD_ING) {
												mRecord_Volume = mRecordUtil
														.getAmplitude();
												mHandler.sendEmptyMessage(RECORD_UPDATE_ANIMATION);
											}
										} catch (InterruptedException e) {
											e.printStackTrace();
										}
									}
								}
							}
						}).start();
					}
					break;
				case MotionEvent.ACTION_UP:
					if (mRecord_State == RECORD_ING) {
						// 修改录音状态
						mRecord_State = RECORD_ED;
						try {
							// 停止录音
							mRecordUtil.stop();
							// 初始录音音量
							mRecord_Volume = 0;
						} catch (IOException e) {
							e.printStackTrace();
						}
						// 如果录音时间小于最短时间
						if (mRecord_Time <= MIN_TIME) {
							// 显示提醒
							Toast.makeText(ChatActivity.this, "录音时间过短",
									Toast.LENGTH_SHORT).show();
							// 修改录音状态
							mRecord_State = RECORD_NO;
							// 修改录音时间
							mRecord_Time = 0;
							// 修改显示界面
							mRecordProgressBar.setProgress(0);
							mRecordLayout.setVisibility(View.GONE);
						} else {
							Message msg = new Message();

							mEntity.setChatAccount(mChatAccount);
							mEntity.setChatType(ChatMsgEntity.PERSON_CHAT);
							mEntity.setIsReaded(ChatMsgEntity.IS_READ);
							mEntity.setIsSended(ChatMsgEntity.SENDED_ING);
							mEntity.setMsgSourse(ChatMsgEntity.IS_SEND_MSG);
							mEntity.setMsgType(ChatMsgEntity.RECORD_FILE);
							mEntity.setPacketId(msg.getPacketID());
							mEntity.setTime(TimeUtil.getCurrentMillisecond());
							mRecordLayout.setVisibility(View.GONE);
							mEntity.setPath(mRecordPath);
							L.i(tag, "filename1:   " + mEntity.getFileName());
							mSendMessageQueue.putEntity(mEntity);
						}
					}
					break;
				}
				return false;
			}

		});
	}

	public void playVoice(final ChatMsgEntity entity) {
		final MediaPlayer mediaPlayer = new MediaPlayer();
		try {
			// 添加录音的路径
			mediaPlayer.setDataSource(MyApplication.getVoiceSavePath()
					+ entity.getFileName());
			// 准备
			mediaPlayer.prepare();
			// 播放
			mediaPlayer.start();

			mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
				// 播放结束后调用
				public void onCompletion(MediaPlayer mp) {
					mediaPlayer.stop();
					android.os.Message msg = mHandler.obtainMessage();
					msg.what = PLAY_VOICE_OVER;
					msg.obj = entity;
					mHandler.sendMessage(msg);
				}
			});

		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void back(View view) {
		finish();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_send:
			String msg = mInputContentET.getText().toString().trim();
			mInputContentET.setText("");
			if (msg.length() > 0) {
				Message message = new Message();
				ChatMsgEntity entity = new ChatMsgEntity();
				entity.setChatAccount(mChatAccount);
				entity.setMsgType(ChatMsgEntity.COMMON_MESSAGE);
				entity.setChatType(ChatMsgEntity.PERSON_CHAT);
				entity.setPacketId(message.getPacketID());
				entity.setIsReaded(ChatMsgEntity.IS_READ);
				entity.setIsSended(ChatMsgEntity.SENDED_ING);
				entity.setMessage(msg);
				entity.setMsgSourse(ChatMsgEntity.IS_SEND_MSG);
				entity.setTime(TimeUtil.getCurrentMillisecond());
				mSendMessageQueue.putEntity(entity);
			} else {
				// 输入窗口为空，不进行发送
				T.showShort(this, "发送消息不能为空");
			}
			break;
		case R.id.ivPopUp:// 点击显示/隐藏录音按钮
			if (btn_vocie) {
				mRecordTV.setVisibility(View.GONE);
				mTextSendLayout.setVisibility(View.VISIBLE);
				btn_vocie = false;
				mOpenRecordIV
						.setImageResource(R.drawable.chatting_setmode_msg_btn);
			} else {
				mRecordTV.setVisibility(View.VISIBLE);
				mTextSendLayout.setVisibility(View.GONE);
				mOpenRecordIV
						.setImageResource(R.drawable.chatting_setmode_voice_btn);
				btn_vocie = true;
			}
			break;

		case R.id.btn_face:// 显示/隐藏表情选择框
			if (view.getVisibility() == View.VISIBLE) {
				view.setVisibility(View.GONE);
			} else {
				view.setVisibility(View.VISIBLE);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void precessMesaage(ChatMsgEntity entity) {// 此方法背底层的子线程调用，不能在此处刷新UI
		android.os.Message msg = mHandler.obtainMessage();
		msg.obj = entity;
		msg.what = GET_MESSAGE;
		mHandler.sendMessage(msg);
	}

	class SendMsgThread extends Thread {
		@Override
		public void run() {
			super.run();
			while (true) {
				ChatMsgEntity entity = mSendMessageQueue.getEntity();
				// 界面退出前会将interupt改为true,并且发一个entity实例，
				// 该实例里面的数据未进行任何处理，因此packetId为null
				if (!interupt && entity.getPacketId() != null) {
					android.os.Message msg = null;
					switch (entity.getMsgType()) {
					case ChatMsgEntity.COMMON_MESSAGE:// 普通消息
						try {
							msg = mHandler.obtainMessage();
							mXmppService.sendChatMessage(entity);
							entity.setIsSended(ChatMsgEntity.SENDED_SUCCESS);
							msg.what = SEND_COMMON_MESSAGE_SUCCESS;
							msg.obj = entity;
						} catch (Exception e) {
							e.printStackTrace();
							msg.what = SEND_COMMON_MESSAGE_EXCEPTION;
							msg.obj = entity;
							entity.setIsSended(ChatMsgEntity.SENDED_FAILED);
						} finally {
							mChatMsgDao.saveOrUpdate(entity);
							mHandler.sendMessage(msg);
						}
						break;
					case ChatMsgEntity.RECORD_FILE:// 录音文件
						try {
							mHandler.sendEmptyMessage(SEND_RECORD_FILE_ING);
							L.i(tag, "filename2:   " + entity.getFileName());
							mXmppService.sendFile(entity);
						} catch (XMPPException e) {
							e.printStackTrace();
							// mHandler.sendEmptyMessage(SEND_RECORD_FILE_FAILED);
						}
						break;
					case ChatMsgEntity.IAMGE_FILE:// 图片
						try {
							mHandler.sendEmptyMessage(SEND_IMAGE_FILE_ING);
							mXmppService.sendFile(entity);
						} catch (XMPPException e) {
							e.printStackTrace();
							// mHandler.sendEmptyMessage(SEND_IMAGE_FILE_FAILED);
						}
						break;
					default:
						break;
					}
				} else {
					// 销毁线程
					break;
				}
			}
		}
	}

	/**
	 * 
	 * 发送消息信息队列
	 * 
	 * @author YINENG
	 * 
	 */
	class SendMessageQueue {
		private final LinkedList<ChatMsgEntity> queue = new LinkedList<ChatMsgEntity>();

		/**
		 * 
		 * 从消息队列中获得出席信息实例
		 * 
		 * @return
		 */
		public synchronized ChatMsgEntity getEntity() {
			while (queue.size() <= 0) {
				try {
					wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			return queue.removeFirst();
		}

		/**
		 * 
		 * 将出席信息实例添加到消息队列
		 * 
		 * @param entity
		 */
		public synchronized void putEntity(ChatMsgEntity entity) {
			queue.addLast(entity);
			notifyAll();
		}
	}

	@Override
	public void fileSendStatus(ChatMsgEntity msg, Status mStatus) {
		android.os.Message message;
		switch (msg.getMsgType()) {
		case ChatMsgEntity.RECORD_FILE:
			if (mStatus == Status.complete) {
				msg.setIsSended(ChatMsgEntity.SENDED_SUCCESS);
				message = mHandler.obtainMessage();
				message.what = SEND_RECORD_FILE_SUCCESS;
				message.obj = msg;
				mHandler.sendMessage(message);
			} else {
				msg.setIsSended(ChatMsgEntity.SENDED_FAILED);
				message = mHandler.obtainMessage();
				message.what = SEND_RECORD_FILE_FAILED;
				message.obj = msg;
				mHandler.sendMessage(message);
			}
			break;
		case ChatMsgEntity.IAMGE_FILE:
			if (mStatus == Status.complete) {
				msg.setIsSended(ChatMsgEntity.SENDED_SUCCESS);
				message = mHandler.obtainMessage();
				message.what = SEND_IMAGE_FILE_SUCCESS;
				message.obj = msg;
				mHandler.sendMessage(message);
			} else {
				msg.setIsSended(ChatMsgEntity.SENDED_FAILED);
				message = mHandler.obtainMessage();
				message.what = SEND_IMAGE_FILE_FAILED;
				message.obj = msg;
				mHandler.sendMessage(message);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void fileReciveStatus(ChatMsgEntity msg, Status status) {
		android.os.Message message;
		switch (msg.getMsgType()) {
		case ChatMsgEntity.RECORD_FILE:
			if (status == Status.complete) {
				message = mHandler.obtainMessage();
				message.what = GET_MESSAGE;
				message.obj = msg;
				mHandler.sendMessage(message);
			}
			break;
		case ChatMsgEntity.IAMGE_FILE:
			if (status == Status.complete) {
				message = mHandler.obtainMessage();
				msg.setIsReaded(ChatMsgEntity.IS_READ);
				mChatMsgDao.saveOrUpdate(msg);
				message.what = GET_MESSAGE;
				message.obj = msg;
				mHandler.sendMessage(message);
			}
			break;
		default:
			break;
		}
	}
}
